package com.shxc.smarttrade.old.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.shxc.smarttrade.R;
import com.shxc.smarttrade.old.activity.AddTradeCategoryActivity;
import com.shxc.smarttrade.old.adapter.EnergyFragmentAdapter;
import com.shxc.smarttrade.MyApplication;
import com.shxc.smarttrade.old.bean.EventDatas;
import com.shxc.smarttrade.old.bean.TradeCategory;
import com.shxc.smarttrade.old.constants.EventContents;
import com.shxc.smarttrade.old.constants.URLContents;
import com.shxc.smarttrade.old.myinterface.TradeCategoryItemClicklistener;
import com.shxc.smarttrade.old.myview.MyProgressDialog;
import com.shxc.smarttrade.old.myview.RecycleViewTwoDivider;
import com.shxc.smarttrade.old.utils.MyOkHttpUtils;
import com.shxc.smarttrade.old.utils.SpUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * Created by jcdev1 on 2017/5/16.
 */

public class EnergyFragment extends Fragment {
    private View rootView;
    RecyclerView rvMoney;
    LinearLayoutManager manager;
    EnergyFragmentAdapter adapter;
    private MyProgressDialog dialog;
    private int userId;

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    //此处表示数据上传成功,需及时提醒前一个界面更新adapter
                    EventBus.getDefault().post(new EventDatas(EventContents.ADD_TRADE_CATEGORY_ACTIVITY_TWO, null));
                    getActivity().finish();
                    break;
            }
        }
    };

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_money, null);
        }
        //缓存的rootView需要判断是否已经被加过parent， 如果有parent需要从parent删除，要不然会发生这个rootview已经有parent的错误。
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }
        initView();
        EventBus.getDefault().register(this);
        return rootView;
    }

    /**
     * 初始化view
     */
    private void initView() {
        userId = SpUtils.getInt(getContext(), "userId", 0);
        dialog = new MyProgressDialog(getContext());
        dialog.setCancelable(false);
        rvMoney = (RecyclerView) rootView.findViewById(R.id.rv_money);
        manager = new LinearLayoutManager(getContext());
        rvMoney.setLayoutManager(manager);
        rvMoney.addItemDecoration(new RecycleViewTwoDivider(getContext(), LinearLayout.HORIZONTAL, 1, getResources().getColor(R.color.dividing_line_color)));
        rvMoney.setAdapter(adapter = new EnergyFragmentAdapter(getContext()));
        adapter.setMyItemClickListener(new TradeCategoryItemClicklistener() {
            @Override
            public void CLickItem(TradeCategory.DataBean.SymbolsBean symbolsBean, int position) {
                //1、上传数据到服务器
                dialog.show();
                if (userId == 0)
                    MyApplication.showToast(getContext(), getString(R.string.data_error));
                else
                    addCategoryToService(userId, symbolsBean.getSymbolEn(), symbolsBean.getSymbolCn());
                //2、上传结束后告知上页及时更改数据、并关闭当前页面
            }
        });

    }

    private void addCategoryToService(int userId, String symbolEn, String symbolCn) {

        Map<String, Object> map = new HashMap<>();
        map.put("accessToken", SpUtils.getString(getContext(), "accessToken", ""));
        map.put("userId", userId + "");
        map.put("symbolEn", symbolEn);
        map.put("symbolCn", symbolCn);
        MyOkHttpUtils.getServiceDatas(getActivity(),map, URLContents.MONEY_FRAGMENT_ADD, new MyOkHttpUtils.ServiceStatus() {
            @Override
            public void faild(Call call, Exception e, int id) {
                MyApplication.showToast(getContext(), getString(R.string.net_error));
                dialog.dismiss();
            }

            @Override
            public void success(String response, int id) {
                JsonObject jsonObject = new JsonParser().parse(response).getAsJsonObject();
                String errCode = jsonObject.get("err_code").getAsString();
                String errMsg = jsonObject.get("err_msg").getAsString();
                if (!errCode.equals("0")) {
                    Toast.makeText(getContext(), errMsg, Toast.LENGTH_SHORT).show();
                } else {
                    Message msg = Message.obtain();
                    msg.what = 0;
                    handler.sendMessage(msg);
                }
                dialog.dismiss();
            }
        });
    }

    /**
     * 必须加注解，否则无效
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(EventDatas event) {
        if (event.getTagOne().equals(EventContents.ADD_TRADE_CATEGORY_ACTIVITY_ONE)) {
            List<TradeCategory.DataBean.SymbolsBean> money = ((AddTradeCategoryActivity) getActivity()).energy;
            adapter.setDatas(money);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
